package technical;

import dao.RssChannelModelDAO;
import exceptions.ExXmlException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import readerRSS.RssChannelModel;
import readerRSS.RssItemModel;
//import service.ServiceRssChannel;

/**
 *
 * @author Tania M
 * @version 1.0
 */
public class ReaderFeedRSS extends ReaderXml {

    /*
     * Pour l'instant: lit RSS 2.0 (spécification la plus récente)
     */
    private URL _url = null;

    /**
     *
     */
    public ReaderFeedRSS() {
        super();
    }

    /**
     *
     * @param obj
     */
    public ReaderFeedRSS(ReaderFeedRSS obj) {
        this._url = obj.getUrl();
    }

    /**
     *
     * @param url
     */
    public ReaderFeedRSS(URL url) {
        super();
        this._url = url;
    }

    //lit un feed: s'il trouve dans la base de données, il le charge
    //et complète en lisant les articles manquants
    public XmlChannelFeedData ReadFeedIncludeDatabases() throws XMLStreamException, ExXmlException {
        
        /*
        XmlChannelFeedData feedLu = null;


        //chargement de la base de données
        RssChannelModelDAO reader = new RssChannelModelDAO();

        ServiceRssChannel serviceTester = new ServiceRssChannel();
        serviceTester.loadOneObject(getUrl().toString());
        RssChannelModel theFoundModel = serviceTester.getObj(); //recupere les modeles

        if (theFoundModel != null) { //si on a trouvé quelque chose dans la base
            //converti theFoundModel en technique 
            //infos du channel
            feedLu = new XmlChannelFeedData(theFoundModel.getTitle(), theFoundModel.getLink(), theFoundModel.getDesc(), theFoundModel.getLang(),
                    null, theFoundModel.getDatePub());
            //infos des items
            for (RssItemModel elt : theFoundModel.getChannelItems()) {
                XmlFeedItemsMessageData feedItems = new XmlFeedItemsMessageData();
                feedItems.setAuthor(null);
                feedItems.setDescription(elt.getDescription());
                feedItems.setGuid(elt.getGuid());
                feedItems.setLink(elt.getLink());
                feedItems.setTitle(elt.getTitle());

                //on ajoute la liste d'item au feed (canal)
                feedLu.getMessages().add(feedItems);
            }
           
        }


        //lecture des articles manquants
        boolean isFeedHeader = true;
        // Set header values intial to the empty string
        String description = "";
        String title = "";
        String link = "";
        String language = "";
        String copyright = "";
        String author = "";
        String pubdate = "";
        String guid = "";

        // STAX: factory
        XMLInputFactory input = XMLInputFactory.newInstance();

        InputStream in = null; //ouverture de l'URL
        try {
            in = getUrl().openStream();
        } catch (IOException ex) {
            Logger.getLogger(ReaderFeedRSS.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (in != null) { //si l'url a pu etre ouverte...

            XMLEventReader eventReader = input.createXMLEventReader(in);
            // Read the XML document
            while (eventReader.hasNext()) { //vérifie s'il y a un element suivant ou non

                XMLEvent event = eventReader.nextEvent(); //comportement type curseur

                if (event.isStartElement()) {
                    //On est en debut de document
                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("item")) {
                        if (isFeedHeader) {
                            isFeedHeader = false;
                            feedLu = new XmlChannelFeedData(title, link, description, language,
                                    copyright, pubdate);
                        }
                        event = eventReader.nextEvent();
                        continue; //si pas de continue, bug...
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("title")) {
                        event = eventReader.nextEvent();
                        title = event.asCharacters().getData();
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("description")) {
                        event = eventReader.nextEvent();
                        try {
                            description = event.asCharacters().getData();
                        } catch (ClassCastException ex) {
                        }
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("link")) {
                        event = eventReader.nextEvent();
                        try {
                            link = event.asCharacters().getData();
                        } catch (Exception ex) {
                            link = event.toString();
                        }
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("guid")) {
                        event = eventReader.nextEvent();
                        guid = event.asCharacters().getData();
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("language")) {
                        event = eventReader.nextEvent();
                        language = event.asCharacters().getData();
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("author")) {
                        event = eventReader.nextEvent();
                        author = event.asCharacters().getData();
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("pubDate")) {
                        event = eventReader.nextEvent();
                        pubdate = event.asCharacters().getData();
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("copyright")) {
                        event = eventReader.nextEvent();
                        copyright = event.asCharacters().getData();
                        continue;
                    }

                } else if (event.isEndElement()) {
                    if (event.asEndElement().getName().getLocalPart().equalsIgnoreCase("item")) {

                        //on passe sur un item...
                        XmlFeedItemsMessageData feed_items = new XmlFeedItemsMessageData();
                        feed_items.setAuthor(author);
                        feed_items.setDescription(description);
                        feed_items.setGuid(guid);
                        feed_items.setLink(link);
                        feed_items.setTitle(title);

                        //on ajoute la liste d'item au feed (canal)

                        feedLu.getMessages().add(feed_items);

                        //suivant
                        event = eventReader.nextEvent();
                        continue;
                    }
                }
            }

        } else {
            throw new ExXmlException("Aucune URL à lire!");
        }

        //*/
        //return feedLu;
        return null;
    }

    /**
     *
     * @return @throws XMLStreamException
     * @throws ExXmlException
     */
    public XmlChannelFeedData Readfeed() throws XMLStreamException, ExXmlException {
        XmlChannelFeedData feedLu = null; //feed lu (channel+items)

        boolean isFeedHeader = true;
        // Set header values intial to the empty string
        String description = "";
        String title = "";
        String link = "";
        String language = "";
        String copyright = "";
        String author = "";
        String pubdate = "";
        String guid = "";

        // STAX: factory
        //try{
        XMLInputFactory input = XMLInputFactory.newInstance();

        InputStream in = null; //ouverture de l'URL
        try {
            in = getUrl().openStream();
        } catch (IOException ex) {
            Logger.getLogger(ReaderFeedRSS.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }

        if (in != null) { //si l'url a pu etre ouverte...

            XMLEventReader eventReader = input.createXMLEventReader(in);
            // Read the XML document
            while (eventReader.hasNext()) { //vérifie s'il y a un element suivant ou non

                XMLEvent event = eventReader.nextEvent(); //comportement type curseur

                if (event.isStartElement()) {
                    //On est en debut de document
                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("item")) {
                        if (isFeedHeader) {
                            isFeedHeader = false;
                            feedLu = new XmlChannelFeedData(title, link, description, language,
                                    copyright, pubdate);
                        }
                        event = eventReader.nextEvent();
                        continue; //si pas de continue, bug...
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("title")) {
                        event = eventReader.nextEvent();
                        try{
                            title = event.asCharacters().getData();
                        } catch (ClassCastException ex) { 
                            title=" ";
                        }
                        
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("description")) {
                        event = eventReader.nextEvent();
                        try{
                        description = event.asCharacters().getData();
                        } catch (ClassCastException ex) { 
                            //System.err.println("Balise link non trouvée ou vide");
                            description=" "; //Comme ça, on n'arrêtera pas l'exécution
                        }
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("link")) {
                        event = eventReader.nextEvent();
                        try {
                            link = event.asCharacters().getData();
                        } catch (ClassCastException ex) { 
                            //System.err.println("Balise link non trouvée ou vide");
                            link=" "; //Comme ça, on n'arrêtera pas l'exécution
                        }
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("guid")) {
                        event = eventReader.nextEvent();
                        guid = event.asCharacters().getData(); //celui_là normalement ne plante pas, il sert à identifier les articles...
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("language")) {
                        event = eventReader.nextEvent();
                        try{
                        language = event.asCharacters().getData();
                        } catch (ClassCastException ex) { 
                            //System.err.println("Balise link non trouvée ou vide");
                            language=" "; //Comme ça, on n'arrêtera pas l'exécution
                        }
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("author")) {
                        event = eventReader.nextEvent();
                        try{
                        author = event.asCharacters().getData();
                        } catch (ClassCastException ex) { 
                            //System.err.println("Balise link non trouvée ou vide");
                            author=" "; //Comme ça, on n'arrêtera pas l'exécution
                        }
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("pubDate")) {
                        event = eventReader.nextEvent();
                        try{
                        pubdate = event.asCharacters().getData();
                        } catch (ClassCastException ex) { 
                            //System.err.println("Balise link non trouvée ou vide");
                            pubdate=" "; //Comme ça, on n'arrêtera pas l'exécution
                        }
                        continue;
                    }

                    if (event.asStartElement().getName().getLocalPart().equalsIgnoreCase("copyright")) {
                        event = eventReader.nextEvent();
                        try{
                        copyright = event.asCharacters().getData();
                        } catch (ClassCastException ex) { 
                            //System.err.println("Balise link non trouvée ou vide");
                            author=" "; //Comme ça, on n'arrêtera pas l'exécution
                        }
                        continue;
                    }

                } else if (event.isEndElement()) {
                    if (event.asEndElement().getName().getLocalPart().equalsIgnoreCase("item")) {

                        //on passe sur un item...
                        XmlFeedItemsMessageData feedItems = new XmlFeedItemsMessageData();
                        feedItems.setAuthor(author);
                        feedItems.setDescription(description);
                        feedItems.setGuid(guid);
                        feedItems.setLink(link);
                        feedItems.setTitle(title);

                        //on ajoute la liste d'item au feed (canal)
                        feedLu.getMessages().add(feedItems);

                        //suivant
                        event = eventReader.nextEvent();
                        continue;
                    }
                }
            }

        } else {
            throw new ExXmlException("Aucune URL à lire!");
        }
        //}catch(Exception ex)
        //        {
        //            ex.printStackTrace();
        //        }

        return feedLu;

    }

    /**
     *
     * @return
     */
    public URL getUrl() {
        return _url;
    }

    /**
     *
     * @param url
     */
    public void setUrl(URL url) {
        this._url = url;
    }

    /*
     * //test... public static void main(String[] args) throws
     * XMLStreamException, MalformedURLException, ExXmlException { ReaderFeedRSS
     * parser = new ReaderFeedRSS(new
     * URL("http://www.developpez.com/index/rss")); XmlChannelFeedData feed_lu =
     * parser.Readfeed(); System.out.println(feed_lu); for
     * (XmlFeedItemsMessageData contenu : feed_lu.getMessages()) {
     * System.out.println(contenu); } } //
     */
}
